/**
 * 客户端路由
 * @param app
 */
module.exports = app => {
    const express = require('express'); //引入express
    const router = express.Router();//创建路由模块
    const usertoken = require('../../usertoken');//token验证模块

    /**
     * ==== 核心路由====
     *
     * 利用动态路由区分接口要连接哪个数据表，动态路由名称==表名
     * 统一做处理，处理完继续往下分发
     */
    app.use('/client/:resource', async (req, res, next) => {
        const modelName = require('inflection').classify(req.params.resource);
        try {
            req.Model = require(`../../models/${modelName}`);
            next()
        } catch (e) {
            next()
        }
    }, router);


    /**
     * 注册登录接口，首次登录判定为注册
     */
    router.post('/login', async (req, res) => {
        const username = req.body.username;
        const user = await req.Model.findOne({username: username})
        if (user != null && (user.password !== req.body.password)) {
            res.send({
                    code: 401,
                    msg: "密码错误"
                }
            )
        }

        if (user == null) {
            //首次登录，插入数据库
            const model = await req.Model.create(req.body);
            const token = usertoken.creatToken(model._id, model.username);
            //登录成功，发放token
            res.send({
                    code: 200,
                    msg: "success",
                    token: token
                }
            )
        } else {
            //非首次登录，验证密码，然后发放token
            if (user.password === req.body.password) {
                //生成Token
                const token = usertoken.creatToken(user._id, user.username);
                res.send({
                        code: 200,
                        msg: "success",
                        token: token
                    }
                )
            }
        }
    });


    /**
     * 获取列表，根据动态路由的名字，取不同的表，返回JSON数据
     */
    router.get('/list', async (req, res) => {
        const list = await req.Model.find().limit(100);
        res.send({
            code: 200,
            msg: "success",
            list
        })
    });


    /**
     * 获取热门列表，按分数排序，无参、
     * 返回JSON数据
     */
    router.get('/hots', async (req, res) => {
        const hots = await req.Model.find().sort({'score': -1}).limit(6);
        let newhot = hots.sort(() => Math.random() - 0.5);
        res.send({
            code: 200,
            msg: "success",
            hots: newhot
        })
    });

    /**
     * 获取搜索默认列表(按分数排序)
     * 获取前端GET请求传入的页码和每页条数，查询数据
     * 返回JSON数据
     */
    router.get('/pulldown', async (req, res) => {
        let page = req.query.page - 1;
        let pageSize = +req.query.pageSize || 10;
        const count = await req.Model.find().count();
        const total = Math.ceil(count / pageSize);
        const pull = await req.Model.find().skip(page * pageSize).limit(pageSize).sort({'score': -1});

        res.send({
            code: 200,
            msg: "success",
            page: page + 1,
            total: total,
            count: count,
            list: pull
        })
    });

    /**
     * 获取搜索列表
     * 获取前端GET提交的关键字参数，查询出电影列表
     * 返回JSON数据
     */
    router.get('/search', async (req, res) => {
        let keywords = req.query.keywords || '';
        let search = '';
        if (keywords) {
            search = await req.Model.find({movieName: {$regex: keywords}});
        } else {
            search = await req.Model.find();
        }
        res.send({
            code: 200,
            msg: "success",
            list: search
        })
    });


    /**
     * 获取电影详情
     * 获取前端GET提交来的电影id
     * 返回电影详情JSON数据
     */
    router.get('/info', async (req, res) => {
        const movieId = req.query.movieId;
        let item = await req.Model.findOne({movieId: movieId});

        item._doc.iscollec = '0';

        if (req.headers.hasOwnProperty('token') && req.headers.token.length > 10) {
            //有登录的用户，判断他有没收藏该片
            const data = await usertoken.verToken(req, res, false).catch((err) => {
            });
            if (data) {
                //先查一下收藏表里面有没有该用户收藏记录
                const collecModel = await require(`../../models/Collection`);
                const collecInfo = await collecModel.findOne({movieId: movieId, customid: data._id});
                if (collecInfo) {
                    item._doc.iscollec = '1';
                }
            }
        }
        res.send({
            code: 200,
            msg: "success",
            item
        })
    });


    /**
     * 用户获取关于我们信息
     */
    router.get('/aboutinfo', async (req, res) => {
        let arrar = [];
        let data1 = {};
        data1.title = "客服QQ";
        data1.text = "339452146";
        arrar.push(data1);
        let data2 = {};
        data2.title = "客服邮箱";
        data2.text = "339452146@qq.com";
        arrar.push(data2);
        res.send({
                code: 200,
                msg: "success",
                data: arrar
            }
        )
    });


    /**
     * 获取个人信息接口
     */
    router.post('/userinfo', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const userinfo = await req.Model.findOne({username: data.username});
        if (userinfo) {
            res.send({
                    code: 200,
                    msg: "success",
                    user: userinfo
                }
            )
        } else {
            res.send(
                {
                    code: 401,
                    msg: "用户不存在"
                }
            )
        }
    });

    /**
     * 用户提交反馈信息
     */
    router.post('/sendfeed', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const insert = req.body;
        insert.customid = data._id;
        insert.username = data.username;
        const model = await req.Model.create(insert);
        if (model) {
            res.send({
                    code: 200,
                    msg: "success",
                }
            )
        } else {
            res.send({
                    code: 500,
                    msg: "服务端错误",
                }
            )
        }
    });

    /**
     * 更新用户信息
     */
    router.post('/upuserinfo', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const item = await req.Model.findByIdAndUpdate(data._id, req.body.userinfo);
        if (item) {
            res.send({
                    code: 200,
                    msg: "success",
                }
            )
        } else {
            res.send({
                    code: 500,
                    msg: "服务端错误",
                }
            )
        }
    });


    /**
     * 点赞一下
     */
    router.post('/likes', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const movieId = req.body.movieId;
        const item = await req.Model.findOne({movieId: movieId})
        let counts = item.counts;
        item.counts = ++counts;
        const newItem = await req.Model.findByIdAndUpdate(item._id, item);
        if (newItem) {
            res.send({
                    code: 200,
                    msg: "success",
                }
            )
        } else {
            res.send({
                    code: 500,
                    msg: "服务端错误",
                }
            )
        }
    });

    /**
     * 添加收藏 and 取消收藏
     */
    router.post('/postcolle', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const customid = data._id;
        const movieId = req.body.movieId;
        const type = req.body.type;
        const item = await req.Model.findOne({movieId: movieId, customid: customid});
        if (type === '1') {
            //收藏
            if (!item) {
                //存入收藏表(先要查出电影表中的数据)
                const movieModel = require(`../../models/Movie`);
                const movieInfo = await movieModel.findOne({movieId: movieId});

                const insertModel = {};
                insertModel.customid = customid;
                insertModel.movieId = movieId;
                insertModel.movieName = movieInfo.movieName;
                insertModel.cover = movieInfo.cover;
                const model = await req.Model.create(insertModel);
                if (model) {
                    res.send({
                            code: 200,
                            msg: "success",
                        }
                    )
                }
            } else {
                //已存在，不能重复收藏
                res.send({
                        code: 401,
                        msg: "操作有误",
                    }
                )
            }
        } else {
            //取消
            if (item) {
                //取消收藏
                const model = await req.Model.deleteOne({movieId: movieId}, req.body);
                if (model) {
                    res.send({
                            code: 200,
                            msg: "success",
                        }
                    )
                }
            } else {
                //根本不存在，取消个毛
                res.send({
                        code: 401,
                        msg: "操作有误",
                    }
                )
            }
        }

    });

    /**
     * 获取我的收藏，暂不分页
     */
    router.get('/colleclist', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const list = await req.Model.find({customid: data._id}).limit(100);
        res.send({
            code: 200,
            msg: "success",
            list
        })
    });


    /**
     * 发表电影评论
     */
    router.post('/sendcomment', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        const insertModel = {};
        insertModel.movieId = req.body.movieId;
        insertModel.customid = data._id;
        insertModel.content = req.body.content;
        const model = await req.Model.create(insertModel);

        if (model) {
            res.send({
                    code: 200,
                    msg: "success",
                }
            )
        } else {
            res.send({
                    code: 500,
                    msg: "服务端错误",
                }
            )
        }
    });

    /**
     * 获取指定电影的评论列表
     */
    router.post('/commentlist', async (req, res) => {
        let list = await req.Model.find({movieId: req.body.movieId}).limit(100);
        for (let item of list) {
            const userModel = require('../../models/User');
            const userInfo = await userModel.findById(item.customid);
            item._doc.headicon = userInfo.headicon;
            item._doc.nickname = userInfo.nickname;
        }
        res.send(
            {
                code: 200,
                msg: "success",
                list
            }
        );
    });

    /**
     * 获取用户自己所有的评论
     */
    router.get('/mycomments', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return
        }
        let list = await req.Model.find({customid: data._id});
        for (let item of list) {
            const movieModel = require('../../models/Movie');
            const movieInfo = await movieModel.findOne({movieId: item.movieId})
            item._doc.movieName = movieInfo.movieName;
            item._doc.cover = movieInfo.cover;
        }
        res.send(
            {
                code: 200,
                msg: "success",
                list
            }
        );
    });


    /**
     * 客户端修改密码
     */
    router.post('/changepwd', async (req, res) => {
        const data = await usertoken.verToken(req, res).catch((err) => {
        });
        if (!data) {
            return;
        }
        const userinfo = await req.Model.findOne({username: data.username});

        if (userinfo.password !== req.body.oldpwd) {
            res.send({
                    code: 401,
                    msg: "原密码错误",
                }
            );
            return;
        }
        if (userinfo.password === req.body.newpwd) {
            res.send({
                    code: 401,
                    msg: "新密码不可与原密码相同",
                }
            );
            return;
        }

        if (req.body.newpwd.length < 6) {
            res.send({
                    code: 401,
                    msg: "密码不可小于6位",
                }
            );
            return;
        }

        userinfo.password = req.body.newpwd;

        const newItem = await req.Model.findByIdAndUpdate(userinfo._id, userinfo);
        if (newItem) {
            res.send({
                    code: 200,
                    msg: "success",
                }
            )
        } else {
            res.send({
                    code: 500,
                    msg: "服务端错误",
                }
            )
        }


    });


};